#!/bin/sh

# stat_line.sh
# count total LINES of FILES of a specific directory, recursively.
# file patterns are claimed by suffix list.

# usage
function usage(){
    echo "usage:";
    echo "$1 dir \"suffix list\"";
    echo "e.g: $1 /home/me \"cpp c h\""
}

function prompt_not_exist {
    echo "$1 doesn't exist!";
}

function prompt_not_directory {
    echo "$1 isn't a directory!";
}

function debug {
    echo "$1" > /dev/null
}

function output {
    echo "$1"
}

# parameter check
if [ $# -lt 2 ]; then
    usage $0;
    exit 1;
fi

# $1 exist?
if [ ! -e $1 ]; then
    prompt_not_exist $1;
    exit 1;
fi

# $1 is a directory?
if [ ! -d $1 ]; then
    prompt_not_directory $1;
    exit 1;
fi
DIR=$1;shift;
# in case of "" or "   "
SUFFIX_LIST=`echo $1`;shift;
debug "suffix list:${SUFFIX_LIST}:"

function stat_line_r {
    ((DIRS=DIRS+1));
    debug "enter $1";

    for item in $1/*;
    do
        debug "pwd $1, list ${item}";
        # in case an empty dir
        if [ ! -e "${item}" ]; then
            debug "${item} not exist, break";
            break;
        fi
        # count lines if a normal file and suffix in list
        if [ ! -d "${item}" ];then
            debug "file ${item}";
            ((FILES=FILES+1));
          if [ '0'"${SUFFIX_LIST}" != '0' ]; then
            # suffix validation
            FIELD_NUM=`basename "${item}" | awk -F"[.]" '{print NF}'`;
            if test ${FIELD_NUM} -le 1 ; then
                SUFFIX='NULL';
            else
                SUFFIX=`basename "${item}" | awk -F"[.]" '{print $NF}'`;
            fi
            debug "${item}=*.${SUFFIX}";
            GOOD_SUFFIX=0;
            for i in ${SUFFIX_LIST};
            do
                if test ''${SUFFIX} = ''${i} ; then
                    ((GOOD_SUFFIX=1));
                    break;
                fi
            done;
            if test ${GOOD_SUFFIX} -eq 0 ; then
                debug "${SUFFIX} NOT in ${SUFFIX_LIST}";
                continue;
            else
                debug "${SUFFIX} in ${SUFFIX_LIST}";
            fi
          fi # if [ ''${SUFFIX_LIST} = '' ]; then
            ((GOOD_FILES=GOOD_FILES+1));
            LINE=`wc -l ${item} | awk -F"[ ]" '{print $1}'`;
            output "${LINE} ${item}"
            let LINES=LINES+LINE;
        # count lines recursively if a dir
        else
            debug "dir ${item}"
            stat_line_r ${item}
        fi
    done
}

LINES=0;
FILES=0;
DIRS=-1;
GOOD_FILES=0;
stat_line_r ${DIR}
echo ""
echo "dir ${DIR}, suffix list \"${SUFFIX_LIST}\""
echo "${DIRS} dirs, ${GOOD_FILES} of ${FILES} files matched, ${LINES} lines"
